package com.salton123.plugin

import com.quinn.hunter.transform.HunterTransform
import com.quinn.hunter.transform.asm.BaseWeaver
import com.salton123.plugin.util.log
import org.gradle.api.Project
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.Opcodes

/**
 * Time:6/21/21 4:57 PM
 * Author:
 * Description:
 */
class ModuleInitTransform(project: Project, var implClass: MutableList<String>) : HunterTransform(project) {

    init {
        this.bytecodeWeaver = object : BaseWeaver() {
            override fun wrapClassWriter(classWriter: ClassWriter?): ClassVisitor {
                return ModuleInitAdapter(classWriter)
            }
        }
    }

    private val TARGET_INTERFACE = "com/salton123/module/api/OnModuleIncubate"
    private val TARGET_CLASS = "com/salton123/module/api/ModuleIncubator"

    inner class ModuleInitAdapter(classWriter: ClassWriter?) : ClassVisitor(Opcodes.ASM7, classWriter) {

        private var className: String? = ""
        override fun visit(
            version: Int, access: Int, name: String?, signature: String?, superName: String?,
            interfaces: Array<out String>?
        ) {
            super.visit(version, access, name, signature, superName, interfaces)
            this.className = name
            interfaces?.forEach {
                if (it == TARGET_INTERFACE) {
                    log("find class:$name")
                    name?.apply {
                        if (this != TARGET_CLASS) {
                            implClass.add(this)
                        }
                    }
                }
            }
        }
    }
}